package com.scott.java.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

import com.scott.java.util.JDBCTools;
import com.scott.java.util.ReflectionUtils;


public class StudentDaoImpl {
	public static <T> T getEntity(Class<T> clazz, String sql, Object... args) throws Exception{
		
		T entity = null;
		entity = clazz.newInstance();
		
		Connection  connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
			//2获取数据库连接
			try {
				connection = JDBCTools.getConnection();
				
				//3创建PreparedStatement 把参数预处理     把参数和sql整合成最终的语句
				//String sql = "select flow_id as flowId,type,id_card idCard,exam_card examCard,student_name studentName,location,grade from exam_student_t t where flow_id=?";
				ps = connection.prepareStatement(sql);
				
				
				//4给问号设值
				for(int i=0; i<args.length;i++){
					ps.setObject(i+1, args[i]);
				}
				
				//5 处理查询得到 结果集
				rs = ps.executeQuery();
				
				//得到 ResultSetMetaData 对象
				ResultSetMetaData rsmd = rs.getMetaData();
				
				//获取列的别名  并放到Map中
				Map<String, Object> map = new HashMap<String, Object>();
				
				//行
				while (rs.next()) {
					//列
					for(int i=0; i< rsmd.getColumnCount(); i++){
						//列的别名  下标从1开始
						String columnLabel = rsmd.getColumnLabel(i+1);
						//System.out.println(columnLabel);
						
						//列的值
						Object columnValue= rs.getObject(columnLabel);
						//System.out.println(columnValue);
						
						map.put(columnLabel, columnValue);
					}
				}
				
				//System.err.println(map);
				
				//为对象的属性赋值
				//遍历map
				for(Map.Entry<String, Object> entry : map.entrySet()){
					
					//属性的名称
					String fieldName = entry.getKey();
					
					//属性的值
					Object fieldValue = entry.getValue();
					
					//System.out.println(fieldName + ":"+fieldValue);
					
					//把object对象的fieldName属性的值设置为fieldValue
					ReflectionUtils.setFieldValue(entity, fieldName, fieldValue);
				}
				
				//System.err.println(entity);
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				JDBCTools.release(rs, ps, connection);
			}
			
		
		return entity;
	}
}
